package me.zhengjie.stock.pipeline;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.stock.domain.TblKline;
import me.zhengjie.stock.service.TblKlineService;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.Date;
import java.util.List;

/**
 * 历史数据存储处理
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class KlineHistoryPipeline implements Pipeline {

    private final TblKlineService klineService;

    @Override
    public void process(ResultItems resultItems, Task task) {
        if (resultItems.isSkip()) {
            return;
        }
        List<TblKline> dataList = resultItems.get("dataList");
        String code = resultItems.get("code");
        String name = resultItems.get("name");
        if (dataList.isEmpty()) {
            log.warn("KlinePipeline Warn!dateList is empty! code:{}, name:{}", code, name);
            return;
        }
        if (dataList.size() == 1) {
            //判断交易数据是否存在
            LambdaQueryWrapper<TblKline> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TblKline::getCode, code);
            queryWrapper.eq(TblKline::getName, name);
            String tradingDate = DateUtil.formatDate(new Date());
            queryWrapper.eq(TblKline::getTradingDate, tradingDate);
            TblKline tblKline = klineService.getOne(queryWrapper);
            TblKline tblKlineNew = dataList.get(0);
            if (tblKline != null) {
                tblKlineNew.setId(tblKline.getId());
                tblKlineNew.setGmtModified(new Date());
                klineService.updateById(tblKlineNew);
            } else {
                klineService.save(tblKlineNew);
            }
        } else {
            klineService.saveBatch(dataList);
        }
        log.info("KlinePipeline success! code:{}, name:{}, size:{}", code, name, dataList.size());

    }
}
